﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace HyCommonTableTool
{
	[Transaction(TransactionMode.Manual)]
	public class CmdAbstractGridFromRevit : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			FilterGroup filterGroup = new FilterGroup();
			Reference reference = null;
			try
			{
				reference = activeUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, filterGroup, "请选择一个表格");
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Group group = document.GetElement(reference) as Group;
			if (group != null)
			{
				List<short> list = new List<short>();
				List<short> list2 = new List<short>();
				List<CellExtendedData> list3 = new List<CellExtendedData>();
				GridDataRefresh refreshData = new GridDataRefresh();
				XYZ ptPos = new XYZ();
				GridExtendedData.ReadGridExtendedData(ref ptPos, group, ref list, ref list2, ref list3, ref refreshData);
				if (list.Count <= 0 || list2.Count <= 0 || list3.Count <= 0)
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
				DlgHyCommonTableTool dlgHyCommonTableTool = new DlgHyCommonTableTool(false);
				GridToolExportImportRevit gridToolExportImportRevit = new GridToolExportImportRevit(commandData, ptPos);
				gridToolExportImportRevit.AbstractGridFromRevit(ref dlgHyCommonTableTool.grid1, list, list2, list3);
				if (dlgHyCommonTableTool.ShowDialog() == DialogResult.OK)
				{
					Transaction transaction = new Transaction(document, "DeleteOldGrid");
					transaction.Start();
					document.Delete(group.Id);
					transaction.Commit();
					if (gridToolExportImportRevit.SetGrid(commandData, dlgHyCommonTableTool.grid1, CREATENEWVIEW.NONE))
					{
						gridToolExportImportRevit.SetRefreshData(refreshData);
						gridToolExportImportRevit.DrawInRevitView();
					}
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
